import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'routes.dart';
import 'services/auth_service.dart';
import 'services/theme_service.dart';
import 'pages/login_page.dart';
import 'pages/main_page.dart';
import 'package:flutter/foundation.dart';
import 'config/app_config.dart';
import 'config/env_loader.dart';
import 'widgets/preview/theme_config_panel.dart';
import 'widgets/common/app_background.dart';
import 'screens/upload_tasks_screen.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';
import 'services/photo_backup_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化环境变量
  await EnvLoader().init();

  // 初始化应用配置
  await AppConfig.init();

  // 初始化设备信息
  final deviceInfo = DeviceInfoPlugin();
  String deviceModel = '';

  try {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfo.androidInfo;
      deviceModel = androidInfo.model;
    } else if (Platform.isIOS) {
      final iosInfo = await deviceInfo.iosInfo;
      deviceModel = iosInfo.utsname.machine;
    }
  } catch (e) {
    debugPrint('获取设备信息失败: $e');
    deviceModel = '未知设备';
  }

  // 设置设备名称到PhotoBackupService
  PhotoBackupService().setDeviceModel(deviceModel);

  // 初始化PhotoBackupService并清理无效记录
  try {
    await PhotoBackupService().initialize();
  } catch (e) {
    debugPrint('初始化PhotoBackupService失败: $e');
  }

  runApp(const ProviderScope(child: MyApp()));
}

/// 应用背景包装器
/// 用于在整个应用中应用背景
class AppBackgroundWrapper extends ConsumerWidget {
  final Widget child;

  const AppBackgroundWrapper({Key? key, required this.child}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return AppBackground(child: child);
  }
}

/// 主题设置按钮 - 可以添加到任何页面
class ThemeSettingsButton extends StatelessWidget {
  final Color? color;
  final double size;

  const ThemeSettingsButton({Key? key, this.color, this.size = 24.0})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.color_lens, color: color, size: size),
      onPressed: () {
        showThemeConfigPanel(context);
      },
      tooltip: '主题设置',
    );
  }
}

/// 显示主题配置面板
void showThemeConfigPanel(BuildContext context) {
  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder:
        (context) => DraggableScrollableSheet(
          initialChildSize: 0.7,
          minChildSize: 0.5,
          maxChildSize: 0.95,
          builder:
              (context, scrollController) =>
                  ThemeConfigPanel(onClose: () => Navigator.pop(context)),
        ),
  );
}

class AuthCheckPage extends ConsumerStatefulWidget {
  const AuthCheckPage({super.key});

  @override
  ConsumerState<AuthCheckPage> createState() => _AuthCheckPageState();
}

class _AuthCheckPageState extends ConsumerState<AuthCheckPage> {
  bool _isLoading = true;
  bool _isLoggedIn = false;

  @override
  void initState() {
    super.initState();
    _checkLoginStatus();
  }

  Future<void> _checkLoginStatus() async {
    final loggedIn = await AuthService.isLoggedIn();

    if (mounted) {
      setState(() {
        _isLoggedIn = loggedIn;
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      // 获取当前主题色
      final themeConfig = ref.read(appThemeConfigProvider);
      final primaryColor = themeConfig.primaryColor;
      final gradientColors = themeConfig.gradientColors;

      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ShaderMask(
                shaderCallback: (Rect bounds) {
                  return LinearGradient(
                    colors: gradientColors,
                  ).createShader(bounds);
                },
                child: const Icon(Icons.pets, size: 80, color: Colors.white),
              ),
              const SizedBox(height: 24),
              CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(primaryColor),
              ),
              const SizedBox(height: 16),
              Text(
                '正在加载...',
                style: TextStyle(
                  color: themeConfig.isDarkMode ? Colors.grey.shade300 : null,
                ),
              ),
            ],
          ),
        ),
        backgroundColor:
            themeConfig.isDarkMode ? const Color(0xFF1C2833) : null,
      );
    }

    if (_isLoggedIn) {
      return const MainPage();
    } else {
      return const LoginPage();
    }
  }
}

class MyApp extends ConsumerWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final themeConfig = ref.watch(appThemeConfigProvider);

    // 捕获全局错误
    FlutterError.onError = (FlutterErrorDetails details) {
      debugPrint('捕获到全局错误: ${details.exception}');
      debugPrint('错误堆栈: ${details.stack}');

      // 仍然将错误报告给Flutter引擎
      FlutterError.presentError(details);
    };

    // 设置内存压力监听器
    WidgetsBinding.instance.addObserver(
      _MemoryPressureObserver(
        onMemoryPressure: () {
          debugPrint('检测到内存压力，尝试释放资源');
          // 释放资源
          PhotoBackupService().pauseAllUploads();
          PaintingBinding.instance.imageCache.clear();
          PaintingBinding.instance.imageCache.clearLiveImages();
        },
      ),
    );

    return MaterialApp(
      title: '咕噜文件',
      theme: themeConfig.toThemeData(),
      debugShowCheckedModeBanner: false,
      onGenerateRoute: Routes.generateRoute,
      home: AppBackgroundWrapper(child: AuthCheckPage()),
    );
  }
}

// 内存压力观察器
class _MemoryPressureObserver extends WidgetsBindingObserver {
  final VoidCallback onMemoryPressure;

  _MemoryPressureObserver({required this.onMemoryPressure});

  @override
  void didHaveMemoryPressure() {
    super.didHaveMemoryPressure();
    onMemoryPressure();
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('文件备份')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '文件备份应用',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 32),
            ElevatedButton.icon(
              icon: const Icon(Icons.cloud_upload),
              label: const Text('上传文件'),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const UploadTasksScreen(),
                  ),
                );
              },
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.sync),
              label: const Text('传输列表'),
              onPressed: () {
                Navigator.pushNamed(context, Routes.transferList);
              },
            ),
          ],
        ),
      ),
    );
  }
}
